<template>
  <a-card size="small" :bordered="false" title="代码生成">
    <a-form v-if="showSearch" layout="inline" :model="params" @submit="handleSearch">
      <a-form-item label="表名称">
        <a-input v-model:value="params.tableName" placeholder="请输入表名称" />
      </a-form-item>
      <a-form-item label="表描述">
        <a-input v-model:value="params.tableComment" placeholder="请输入表描述" />
      </a-form-item>
      <a-form-item label="创建时间">
        <a-range-picker @ok="handleDateChoose" @change="handleDateChoose" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" :loading="tableLoading" html-type="submit">
          <template #icon><SearchOutlined /></template>
          <span v-if="!tableLoading">搜索</span>
          <span v-else>搜索中...</span>
        </a-button>
      </a-form-item>
    </a-form>
    <table-toolbar
      v-model:show-search="showSearch"
      v-model:columns="tableColumns"
      style="margin-top: 10px"
      @reload="handleLoadData"
    >
      <template #left>
        <a-button type="primary" @click="handleImport">
          <template #icon><CloudUploadOutlined /></template>
          导入
        </a-button>

        <a-button type="primary" :disabled="!hasSelectOne" @click="handleEditToolbar">
          <template #icon><EditOutlined /></template>
          编辑
        </a-button>

        <a-button type="primary" danger :disabled="!hasSelected" @click="handleDelToolbar">
          <template #icon><DeleteOutlined /></template>
          删除
        </a-button>
      </template>
    </table-toolbar>

    <a-table
      :loading="tableLoading"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange
      }"
      :columns="tableColumns"
      :data-source="tableDataSource"
      :pagination="pageInfo"
      row-key="tableId"
      size="middle"
      @change="handlePageChange"
    >
      <template #bodyCell="{ index, column, record }">
        <template v-if="column.key === 'serialId'">
          {{ (params.current - 1) * params.size + index + 1 }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-button size="small" style="margin-right: 5px" @click="handlePreview(record.tableId)">
            <template #icon><FileTextOutlined /></template>
            预览
          </a-button>
          <a-button type="primary" size="small" style="margin-right: 5px" @click="handleEdit(record.tableId)">
            <template #icon><FormOutlined /></template>
            编辑
          </a-button>
          <a-button size="small" style="margin-right: 5px" @click="handleSync(record.tableName)">
            <template #icon><ReloadOutlined /></template>
            同步
          </a-button>
          <a-popconfirm title="确定删除吗?" ok-text="确定" cancel-text="取消" @confirm="handleDel(record.tableId)">
            <a-button type="primary" danger size="small" style="margin-right: 5px">
              <template #icon><DeleteOutlined /></template>
              删除
            </a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>

    <import-table ref="importRef" @reload="handleLoadData"></import-table>
    <gen-edit ref="editRef" @reload="handleLoadData"></gen-edit>

    <a-modal v-model:visible="preview.visible" title="代码预览" :footer="null" :width="'80%'">
      <a-tabs v-model:activeKey="preview.activeName">
        <a-tab-pane
          v-for="(value, key) in preview.data"
          :key="key"
          :tab="key"
        >
          <!-- eslint-disable vue/no-v-html -->
          <pre><code class="hljs" v-html="handleHighlightedCode(value, key)"></code></pre>
        </a-tab-pane>
      </a-tabs>
    </a-modal>
  </a-card>
</template>

<script name="ToolGenIndex" lang="ts" setup>
import type { Dayjs } from "dayjs";
import { isNull } from "lodash-es";
import hljs from "highlight.js/lib/core";
import java from "highlight.js/lib/languages/java";
import xml from "highlight.js/lib/languages/xml";
import javascript from "highlight.js/lib/languages/javascript";
import "highlight.js/styles/idea.css";
import { getTimestampDayBegin } from "@/utils/time";
import { delGenTable, getPage, previewTable, syncGenTable } from "@/api/tool/gen";
import ImportTable from "./import.vue";
import GenEdit from "./edit.vue";
import type {TabsProps} from "ant-design-vue";

const showSearch = ref<boolean>(true);
const params = reactive<any>({
  tableName: "",
  tableComment: "",
  startCreateTime: undefined,
  endCreateTime: undefined
});
const handleDateChoose = (dates: [Dayjs, Dayjs]) => {
  if (!isNull(dates)) {
    params.startCreateTime = getTimestampDayBegin(dates[0]);
    params.endCreateTime = getTimestampDayBegin(dates[1]);
  }
};

//表格
const tableColumns = reactive<TableColumn[]>([
  {
    key: "serialId",
    dataIndex: "serialId",
    title: "序号"
  },
  {
    key: "tableName",
    dataIndex: "tableName",
    title: "表名称"
  },
  {
    key: "tableComment",
    dataIndex: "tableComment",
    title: "表描述"
  },
  {
    key: "createTime",
    dataIndex: "createTime",
    title: "创建时间"
  },
  {
    key: "updateTime",
    dataIndex: "updateTime",
    title: "更新时间"
  },
  {
    key: "action",
    title: "操作",
    fixed: "right"
  }
]);

const { tableLoading, pageInfo, tableDataSource, handleLoadData, handlePageChange, handleSearch } = useTablePage(
  params,
  getPage
);

const { selectId, selectedRowKeys, selectedRows, hasSelected, hasSelectOne, onSelectChange } = useTableSelect();

const importRef = ref();
const handleImport = () => {
  importRef.value.show();
};

const editRef = ref();
const handleEdit = (tableId: number) => {
  editRef.value.show(tableId);
};
const handleEditToolbar = () => {
  handleEdit(selectId.value);
};

const handleDelToolbar = () => {
  antdModal.confirm({
    title: "警告",
    icon: createVNode(ExclamationCircleOutlined),
    content: "你确定要删除选中的表吗?",
    onOk() {
      tableLoading.value = true;
      delGenTable(selectedRowKeys.value)
        .then(() => {
          handleLoadData();
          antdMessage.success("删除成功");
        })
        .finally(() => {
          tableLoading.value = false;
        });
    }
  });
};

const handleDel = (id: number) => {
  tableLoading.value = true;
  delGenTable(id)
    .then(() => {
      handleLoadData();
      antdMessage.success("删除成功");
    })
    .finally(() => {
      tableLoading.value = false;
    });
};

const handleSync = (tableName: string) => {
  antdModal.confirm({
    title: "警告",
    icon: createVNode(ExclamationCircleOutlined),
    content: "确认要强制同步" + tableName + "表结构吗?",
    onOk() {
      tableLoading.value = true;
      syncGenTable(tableName)
        .then(() => {
          antdMessage.success("同步成功");
        })
        .finally(() => {
          tableLoading.value = false;
        });
    }
  });
};

//预览
const preview = reactive({
  visible: false,
  activeName: "",
  data: []
});
const handlePreview = (tableId: number) => {
  preview.visible = true;
  previewTable(tableId).then(response => {
    preview.data = response.data;
    preview.activeName = response.data[0];
  });
};

//高亮显示
hljs.registerLanguage("java", java);
hljs.registerLanguage("xml", xml);
hljs.registerLanguage("ts", javascript);
hljs.registerLanguage("vue", javascript);

const handleHighlightedCode = (code: string, key: string) => {
  const language = key.substring(key.indexOf(".") + 1, key.length);
  const result = hljs.highlight(code || "", { language });
  return result.value || "&nbsp;";
};

onMounted(() => {
  handleLoadData();
});
</script>
